$(function(){
    //发送验证码
    var sendCodeUrl = '/person/sendPhoneCode?token='+localStorage.getItem('token')+'&type=register';
    //绑定手机号
    var changePhoneUrl = '/personSet/changePhone';

    //验证手机号
    function checkTel(tel){
        var exg = /^1[34578]\d{9}$/;
        if(tel.match(exg)){
            return true;
        }else{
            return false;
        }
    }
    //点击发送验证码
    $(".getCode").click(function(){
        var tel = $("[name='mobile']").val();
        if(tel == ''){
            $(".bxg-alert-tip").html("请输入手机号").show();
            setTimeout(function(){
                $(".bxg-alert-tip").fadeOut();
            },2000);
        }else if(!checkTel(tel)){
            $(".bxg-alert-tip").html("手机号不存在").show();
            setTimeout(function(){
                $(".bxg-alert-tip").fadeOut();
            },2000);
        }else{
            time();
            sendCodeUrl = sendCodeUrl+'&phone='+tel;
            $.getJSON(sendCodeUrl,function (data) {
               if (data.success) {
                   alert('已发送验证码');
               } else {
                   //绑定失败
                   $(".bxg-alert-tip").html(data.message).show();
               }
            });
        }
    });

    $(".bxg-submit").click(function(){
        var tel = $("[name='mobile']").val();
        var code = $("[name='code']").val();
        if(code != ''){
            var url= changePhoneUrl+'?phone='+tel+'&code='+code;
            $.ajax({
                url:url,
                type:"GET",
                data:format,
                contentType:false,
                processData:false,
                cache:false,
                beforeSend: function(request){
                    request.setRequestHeader("Token",localStorage.getItem('token'));
                },
                success:function (data) {
                    if (data.success) {
                        //跳转到绑定成功的页面
                        window.location.href = "/person/bindSuccess";
                    }else {
                        $(".bxg-alert-tip").html(data.message).show();
                    }
                }
            });
        }else{
            $(".bxg-alert-tip").html("请输入验证码").show();
            setTimeout(function(){
                $(".bxg-alert-tip").fadeOut();
            },2000);
        }
    });


    var wait=60;
    function time() {
        if (wait == 0) {
            $('.getCode').html('获取验证码').attr('disable',false);
            wait = 60;
        } else {
            $('.getCode').html(wait+'秒').attr("disabled", true);
            wait--;
            setTimeout(function() {
                    time()
                },
                1000)
        }
    }
})
